<template>
  <el-carousel height="300px" type="card" >
    <el-carousel-item v-for="item in data.carouselData" :key="item">
      <img :src="item" alt="" style="width: 100%; height: 300px">
    </el-carousel-item>
  </el-carousel>
  <div class="main-container" style="margin-top: 20px">
    <div class="container">
      <div class="left-div">
        <el-carousel :interval="3000" :autoplay="true" height="400px" style="border-radius: 15px;">
          <el-carousel-item v-for="(news, index) in carouselImages" :key="index">
            <img
                :src="news.noticeImg"
                style="width: 100%; height: 100%; object-fit: cover;"
                alt=""
                @click="navTo(`/front/noticeDetail?id=${news.id}`)"
            >
          </el-carousel-item>
        </el-carousel>
      </div>
      <div class="right-div">
        <div class="tab-header" ref="tabHeader">
          <h3>{{ selectedTab === 'news' ? '新闻资讯' : '小测公告' }}</h3>
          <div class="tab-buttons">
            <span
                class="tab-button"
                :class="{ active: selectedTab === 'news' }"
                @click="selectTab('news')"
            >
              新闻资讯
            </span>
            <span
                class="tab-button"
                :class="{ active: selectedTab === 'examPlan' }"
                @click="selectTab('examPlan')"
            >
              小测公告
            </span>
          </div>
        </div>
        <div class="news-list">
          <div
              v-for="(item, index) in paginatedData"
              :key="index"
              class="news-item"
              @click="navTo(`/front/noticeDetail?id=${item.id}`)"
          >
            <div class="news-title-time">
              <div class="news-title">{{ item.title }}</div>
              <div class="news-time">{{ item.time }}</div>
            </div>
          </div>
        </div>
        <div class="pagination">
          <el-pagination
              @current-change="handlePageChange"
              background
              layout="prev, pager, next"
              :total="paginatedTotal"
              :page-size="data.pageSize"
              v-model:current-page="currentPage"
          />
        </div>
      </div>
    </div>
    <div style="font-size: 18px; display: flex; margin-top: 20px; justify-content: space-between; width: 100%;">
      <div style="flex: 1; text-align: left;">正在进行中的小测</div>
      <div style="width: 100px; text-align: right; color: #666666; font-size: 15px; cursor: pointer;" @click="navTo('/front/exam')">查看更多</div>
    </div>
    <div class="test-paper-container">
      <el-row :gutter="20">
        <el-col :span="6" v-for="paper in data.examData" :key="paper.id" style="margin-bottom: 20px">
          <div class="card" @click="navTo(paper)">
            <img :src="paper.courseImg" alt="" class="card-image">
            <div class="card-content">
              <div class="overflowShow card-title">{{ paper.paperName }}</div>
              <div style="display: flex; align-items: center; margin-top: 10px;">
                <img :src="paper.teacherAvatar" alt="" class="user-avatar">
                <div class="teacher-name" style="flex: 1; margin-left: 10px;">{{ paper.teacherName }}</div>
                <div class="exam-status" style="text-align: right;">
                  <el-tag v-if="paper.status === '进行中'" type="success">{{ paper.status }}</el-tag>
                  <el-tag v-if="paper.status === '未开始'" type="warning">{{ paper.status }}</el-tag>
                  <el-tag v-if="paper.status === '已结束'" type="danger">{{ paper.status }}</el-tag>
                </div>
              </div>
              <div class="course-info" style="margin-top: 10px;">课程名称：{{ paper.courseName }}</div>
              <div class="date-info" style="margin-top: 10px;">开放时间：{{ formattedDate(paper.startDatetime) }} ~ {{ formattedDate(paper.endDatetime) }}</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- Plant Guide Section -->
    <div style="font-size: 18px; display: flex; margin-top: 20px; justify-content: space-between; width: 100%;">
      <div style="flex: 1; text-align: left;">随机推荐的植物指南</div>
      <div style="width: 100px; text-align: right; color: #666666; font-size: 15px; cursor: pointer;" @click="loadPlantGuides">刷新</div>
    </div>
    <div class="plant-guide-container">
      <el-row :gutter="20">
        <el-col :span="6" v-for="guide in data.plantGuides" :key="guide.id" style="margin-bottom: 20px">
          <div class="card" @click="navTo(`/front/plantGuideDetail?id=${guide.id}`)">
            <img :src="guide.img" alt="" class="card-image">
            <div class="card-content">
              <div class="overflowShow card-title">{{ guide.title }}</div>
              <div style="display: flex; align-items: center; margin-top: 10px;">
                <div class="teacher-name" style="flex: 1; margin-left: 10px;">{{ guide.createdByUsername }}</div>
                <div class="exam-status" style="text-align: right;">
                  <el-tag type="info">{{ guide.updatedAt.split(' ')[0] }}</el-tag>
                </div>
              </div>
              <div class="course-info" style="margin-top: 10px;">植物名称：{{ guide.plantChineseName }}</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from "vue";
import carousel_1 from "@/assets/imgs/carousel-1.jpg";
import carousel_2 from "@/assets/imgs/carousel-2.jpg";
import carousel_3 from "@/assets/imgs/carousel-3.jpg";
import carousel_4 from "@/assets/imgs/carousel-4.jpg";
import request from "@/utils/request.js";
import { ElMessage } from "element-plus";

const data = reactive({
  carouselData: [carousel_1, carousel_2, carousel_3,carousel_4],
  examData: [],
  examPlanData: [],
  newsData: [],
  plantGuides: [], // New field for plant guides
  dialogVisible: false,
  form: {
    noticeImg: '',
  },
  pageNum: 1,
  pageSize: 5,
  total: 0,
});

const currentPage = ref(1);
const selectedTab = ref('news'); // 默认显示新闻资讯

const loadNews = () => {
  request.post('/newInfo/selectPage', {
    pageNum: data.pageNum,
    pageSize: data.pageSize,
    title: '',
    noticeCategory: 2,
    status: ''
  }).then(res => {
    if (res.code === '200') {
      data.newsData = res.data.list;
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    console.error("Error loading newInfo:", err);
    ElMessage.error("加载新闻资讯失败，请稍后再试");
  });
};

const loadExamPlan = () => {
  request.post('/notice/selectPage', {
    pageNum: data.pageNum,
    pageSize: data.pageSize,
    title: '',
    noticeCategory: 1
  }).then(res => {
    if (res.code === '200') {
      data.examPlanData = res.data?.list || [];
      data.total = res.data?.total;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const handlePageChange = (page) => {
  currentPage.value = page;
  loadData();
};

const selectTab = (tab) => {
  selectedTab.value = tab;
  currentPage.value = 1; // 切换标签时重置到第一页
  loadData();
};

const loadData = () => {
  if (selectedTab.value === 'news') {
    loadNews();
  } else if (selectedTab.value === 'examPlan') {
    loadExamPlan();
  }
};

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * data.pageSize;
  const end = start + data.pageSize;
  return selectedTab.value === 'news' ? data.newsData.slice(start, end) : data.examPlanData.slice(start, end);
});

const paginatedTotal = computed(() => {
  return selectedTab.value === 'news' ? data.newsData.length : data.examPlanData.length;
});

const carouselImages = computed(() => {
  return data.newsData.slice(0, 5);
});

const navTo = (item) => {
  if (typeof item === 'string') {
    location.href = item;
  } else if (item.status === '未开始') {
    ElMessage.warning('该小测还未开放');
    return;
  } else if (item.status === '已结束') {
    ElMessage.warning('该小测已结束');
    return;
  }
  request.get('/testPaper/check/' + item.id).then(res => {
    if (res.code === '200') {
      location.href = '/front/testPaper?id=' + item.id;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const loadTestPaper = () => {
  request.get('/testPaper/selectRandom').then(res => {
    if (res.code === '200') {
      data.examData = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const loadPlantGuides = () => {
  request.get('/plantGuide/selectRandom').then(res => {
    if (res.code === '200') {
      data.plantGuides = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const formattedDate = (dateString) => {
  const options = { year: 'numeric', month: 'long', day: 'numeric' };
  return new Date(dateString).toLocaleDateString(undefined, options);
};

onMounted(() => {
  loadNews(); // 初始化数据加载
  loadExamPlan();
  loadTestPaper();
  loadPlantGuides(); // 加载植物指南
});
</script>

<style scoped>
body {
  margin: 0;
  padding: 0;
  height: 100vh;
  background-color: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.main-container {
  width: calc(100% - 360px); /* Total width minus left and right padding */
  max-width: 1200px; /* Optional: Set a maximum width */
  margin: auto; /* 水平居中 */
  display: flex;
  flex-direction: column; /* 确保子元素垂直排列 */
  align-items: center;
  height: auto; /* 自动高度以适应内容 */
}

.container {
  display: flex;
  width: 100%;
  height: 400px; /* 确保容器高度一致 */
}

.left-div {
  width: 50%;
  height: 400px;
  border-radius: 15px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background-color: white;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  color: #333;
}

.right-div {
  width: 50%;
  height: 400px;
  border-radius: 15px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background-color: white;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 20px;
  box-sizing: border-box;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.news-list {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 10px;
}

.news-item {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}

.news-item:last-child {
  border-bottom: none;
}

.news-title-time {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.news-title {
  font-weight: bold;
  font-size: 16px;
}

.news-time {
  font-size: 12px;
  color: #777;
}

.pagination {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.tab-buttons {
  display: flex;
  gap: 10px;
}

.tab-button {
  cursor: pointer;
  padding: 8px 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  background-color: #f9f9f9;
  transition: background-color 0.3s, border-color 0.3s;
}

.tab-button.active {
  background-color: #409EFF;
  color: white;
  border-color: #409EFF;
}

.tab-button:hover {
  background-color: #ecf5ff;
  border-color: #c6e2ff;
}

.tab-button.active:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.test-paper-container {
  width: calc(100%); /* Total width minus left and right padding */
  max-width: 1200px; /* Optional: Set a maximum width */
  margin-top: 20px;
  left: 0;
}

.card {
  position: relative;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
  cursor: pointer;
  overflow: hidden;
  background-color: #fff;
  height: 100%;
}

.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}

.card-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.card-content {
  padding: 15px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
}

.user-avatar {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  object-fit: cover;
}

.teacher-name {
  font-size: 14px;
  color: #666666;
}

.exam-status .el-tag {
  margin-left: 5px;
}

.course-info {
  font-size: 14px;
  color: #7f8c8d;
}

.date-info {
  font-size: 14px;
  color: #999999;
}

.overflowShow {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.el-col {
  width: calc(20% - 20px); /* Ensure each column takes up 20% minus gutter */
  box-sizing: border-box;
}

.plant-guide-container {
  width: calc(100%);
  max-width: 1200px;
  margin-top: 20px;
  left: 0;
}
</style>
